package com.dsh.modbus;
import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import com.intelligt.modbus.jlibmodbus.tcp.TcpParameters;

import java.net.InetAddress;

public class ModbusExample {
    public static final String IP = "192.168.12.225";

    public static void main(String[] args) throws  Exception{
        TcpParameters tcpParameters = new TcpParameters();
        InetAddress inetAddress = InetAddress.getByName(IP);
        tcpParameters.setHost(inetAddress); // 替换为实际IP
        tcpParameters.setPort(502);
        tcpParameters.setKeepAlive(true);

        ModbusMaster master = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
        Modbus.setAutoIncrementTransactionId(true);

        int maxRetries = 3;
        int retryCount = 0;
        boolean connected = false;

        while (retryCount < maxRetries && !connected) {
            try {
                if (!master.isConnected()) {
                    master.connect();
                    connected = true;
                    System.out.println("Modbus连接成功");
                }

                // 读取保持寄存器示例
                int slaveId = 1;
                int startAddress = 0;
                int quantity = 10;
                int [] registers = master.readHoldingRegisters(slaveId, startAddress, quantity);
                // 处理返回数据...

            } catch (Exception e) {
                System.err.println("Modbus通信失败（尝试 " + (retryCount + 1) + "/" + maxRetries + "）: " + e.getMessage());
                retryCount++;
                try {
                    Thread.sleep(1000); // 重试前等待1秒
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                }
            } finally {
                try {
                    if (master.isConnected()) {
                        master.disconnect();
                    }
                } catch (Exception e) {
                    System.err.println("断开连接失败: " + e.getMessage());
                }
            }
        }

        if (!connected) {
            System.err.println("达到最大重试次数，连接失败");
        }
    }
}